class Snake {
  constructor() {
    this.dir = 'right'
    this.body = [{ x: 3, y: 5 }, { x: 4, y: 5 }, { x: 5, y: 5 }]
  }

  move() {
    this.body = this.getBody()
  }

  getBody() {
    const _snake = []
    for (let i = 1; i < this.body.length; i++) {
      _snake.push(this.body[i])
    }

    _snake.push(this.getHead())
    return _snake
  }

  getHead() {
    const last = this.body[this.body.length - 1]
    let head = {}
    switch (this.dir) {
      case 'left': head = { x: last.x - 1, y: last.y }; break;
      case 'up': head = { x: last.x, y: last.y - 1 }; break;
      case 'right': head = { x: last.x + 1, y: last.y }; break;
      case 'down': head = { x: last.x, y: last.y + 1 }; break;
    }
    return head
  }

  isEatSelf() {
    const head = this.body[this.body.length - 1]
    for (let i = 0; i < this.body.length - 1; i++) {
      let s = this.body[i]
      if (s.x === head.x && s.y === head.y) {
        return true
      }
    }
    return false
  }

  turnLeft() {
    if (this.dir !== 'right') {
      this.dir = 'left'
    }
  }
  turnRight() {
    if (this.dir !== 'left') {
      this.dir = 'right'
    }
  }
  turnUp() {
    if (this.dir !== 'down') {
      this.dir = 'up'
    }
  }
  turnDown() {
    if (this.dir !== 'up') {
      this.dir = 'down'
    }
  }
}
